import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { motion } from 'framer-motion';
import { Check, ArrowRight, Sparkles } from 'lucide-react';
import { useInterestStore, useAuthStore } from '../stores';
import { apiService } from '../services/api';
import toast from 'react-hot-toast';
import type { InterestTag } from '../types/api';

const InterestSelectionPage: React.FC = () => {
  const navigate = useNavigate();
  const { user } = useAuthStore();
  const { 
    availableTags, 
    selectedTags, 
    setAvailableTags, 
    addTag, 
    removeTag 
  } = useInterestStore();
  
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);

  // 获取兴趣标签列表
  useEffect(() => {
    const fetchInterestTags = async () => {
      try {
        const response = await apiService.getInterestTags();
        if (response.code === 0) {
          setAvailableTags(response.data.tags);
        }
      } catch (error) {
        console.error('Fetch interest tags error:', error);
        toast.error('获取兴趣标签失败');
      } finally {
        setIsLoading(false);
      }
    };

    fetchInterestTags();
  }, [setAvailableTags]);

  // 保存用户兴趣选择
  const handleSaveInterests = async () => {
    if (selectedTags.length === 0) {
      toast.error('请至少选择一个兴趣标签');
      return;
    }

    if (!user) {
      toast.error('用户信息不存在');
      return;
    }

    setIsSaving(true);
    try {
      const response = await apiService.saveUserInterests({
        user_id: user.user_id,
        tag_ids: selectedTags.map(tag => tag.tag_id),
      });

      if (response.code === 0) {
        toast.success('兴趣选择保存成功！');
        navigate('/home');
      }
    } catch (error) {
      console.error('Save interests error:', error);
    } finally {
      setIsSaving(false);
    }
  };

  const toggleTag = (tag: InterestTag) => {
    if (selectedTags.some(t => t.tag_id === tag.tag_id)) {
      removeTag(tag.tag_id);
    } else {
      addTag(tag);
    }
  };

  // 按分类分组标签
  const groupedTags = availableTags.reduce((acc, tag) => {
    if (!acc[tag.category]) {
      acc[tag.category] = [];
    }
    acc[tag.category].push(tag);
    return acc;
  }, {} as Record<string, InterestTag[]>);

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="w-8 h-8 border-2 border-primary-500 border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-gray-600">加载兴趣标签中...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 pt-20">
      <div className="max-w-2xl mx-auto px-4">
        {/* 页面标题 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="text-center mb-8"
        >
          <div className="w-16 h-16 bg-gradient-to-br from-primary-500 to-secondary-500 rounded-full mx-auto mb-4 flex items-center justify-center">
            <Sparkles className="text-white" size={32} />
          </div>
          <h1 className="text-2xl font-bold text-gray-900 mb-2">选择你的兴趣</h1>
          <p className="text-gray-600">告诉我们你的兴趣爱好，帮你找到志同道合的朋友</p>
        </motion.div>

        {/* 兴趣标签 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2 }}
          className="space-y-6"
        >
          {Object.entries(groupedTags).map(([category, tags]) => (
            <div key={category} className="bg-white rounded-xl p-6 shadow-sm">
              <h3 className="text-lg font-semibold text-gray-900 mb-4">{category}</h3>
              <div className="grid grid-cols-2 gap-3">
                {tags.map((tag) => {
                  const isSelected = selectedTags.some(t => t.tag_id === tag.tag_id);
                  return (
                    <motion.button
                      key={tag.tag_id}
                      whileHover={{ scale: 1.02 }}
                      whileTap={{ scale: 0.98 }}
                      onClick={() => toggleTag(tag)}
                      className={`p-3 rounded-lg border-2 transition-all duration-200 ${
                        isSelected
                          ? 'border-primary-500 bg-primary-50 text-primary-700'
                          : 'border-gray-200 bg-white text-gray-700 hover:border-primary-300 hover:bg-primary-25'
                      }`}
                    >
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-medium">{tag.tag_name}</span>
                        {isSelected && (
                          <Check className="text-primary-500" size={16} />
                        )}
                      </div>
                    </motion.button>
                  );
                })}
              </div>
            </div>
          ))}
        </motion.div>

        {/* 已选择标签预览 */}
        {selectedTags.length > 0 && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.4 }}
            className="mt-6 bg-white rounded-xl p-6 shadow-sm"
          >
            <h3 className="text-lg font-semibold text-gray-900 mb-4">
              已选择 ({selectedTags.length})
            </h3>
            <div className="flex flex-wrap gap-2">
              {selectedTags.map((tag) => (
                <span
                  key={tag.tag_id}
                  className="px-3 py-1 bg-primary-100 text-primary-700 rounded-full text-sm font-medium"
                >
                  {tag.tag_name}
                </span>
              ))}
            </div>
          </motion.div>
        )}

        {/* 保存按钮 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.6 }}
          className="mt-8 pb-8"
        >
          <motion.button
            whileHover={{ scale: 1.02 }}
            whileTap={{ scale: 0.98 }}
            onClick={handleSaveInterests}
            disabled={isSaving || selectedTags.length === 0}
            className="w-full btn-primary flex items-center justify-center space-x-2 py-4 text-lg"
          >
            {isSaving ? (
              <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
            ) : (
              <>
                <span>完成选择</span>
                <ArrowRight size={20} />
              </>
            )}
          </motion.button>
          
          <p className="text-center text-gray-500 text-sm mt-4">
            选择至少3个兴趣标签，帮助我们更好地为你推荐
          </p>
        </motion.div>
      </div>
    </div>
  );
};

export default InterestSelectionPage;
